package com.glink.manage.service.Impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.common.contants.BaseCodeConstants;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.common.*;
import com.glink.manage.common.enums.MqttEnum;
import com.glink.manage.domain.*;
import com.glink.manage.dto.person.*;
import com.glink.manage.dto.user.UserSaveDTO;
import com.glink.manage.mapper.PersonManageMapper;
import com.glink.manage.service.*;
import com.glink.manage.vo.barriergate.PersonSyncDetailInfoVO;
import com.glink.manage.vo.code.CodeVO;
import com.glink.manage.vo.org.OrgBaseInfoVO;
import com.glink.manage.vo.org.OrgIdRequestDTO;
import com.glink.manage.vo.org.OrgPersonInfoVO;
import com.glink.manage.vo.person.*;
import com.glink.manage.vo.temporaryadmission.TemporaryAdmissionCheckWorkVO;
import com.glink.manage.vo.user.UserBaseInfoVO;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author  qiushaoshan
 * @since 2025-01-13
 */
@Service
@Slf4j
public class PersonManageServiceImpl extends ServiceImpl<PersonManageMapper, PersonManageBean> implements PersonManageService {

    @Autowired
    private PersonCertService personCertService;
    
    @Autowired
    private PersonViolationRegulationsRecordService personViolationRegulationsRecordService;
    
    @Autowired
    private PersonTrainingRecordService personTrainingRecordService;
    
    @Autowired
    private ParticipatingUnitService participatingUnitService;
    
    @Autowired
    private CodeService codeService;
    
    @Autowired
    private ConstructionWorkService constructionWorkService;
    
    @Autowired
    private BlacklistService blacklistService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OrgService orgService;
    
    @Autowired
    private PersonAccessRelaService personAccessRelaService;
    
    @Autowired
    private VehicleService vehicleService;

    @Autowired
    @Lazy
    private BarrierGateService barrierGateService;
    
    @Autowired
    private AttachmentService attachmentService;
    
    @Autowired
    @Lazy
    private TemporaryAdmissionService temporaryAdmissionService;
    
    @Autowired
    @Lazy
    private SilentResultService silentResultService;
    
    @Value("${participatingUnitTree.name:参建单位}")
    private String participatingUnitTreeName;

    @Value("${participatingUnitTree.id:0}")
    private String participatingUnitTreeId;

    public static final String GET_FILE_PATTERN = "file:";
    private static final String ZIP_FILE = "application/zip";
    private static final String ZIP_FILE2 = "application/x-zip-compressed";
    private static final String RAR_FILE = "application/vnd.rar";
    private static final String RAR_FILE2 = "application/x-rar-compressed";

    @Value("${spring.resources.static-locations:E:\\qss\\test\\zip\\}")
    public String IMAGE_BASE_DIR;

    @Value("${spring.servlet.multipart.max-file-size:50mb}")
    private String FILE_LENGTH;

    // 黑名单的年龄标准
    @Value("${blacklist.age.level:60}")
    private Integer blacklistAgeLevel;
    
    /**
     * 新增人员信息
     *
     * @param dto 人员信息
     * @return 新增状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String insertPerson(PersonManageSaveDTO dto) throws GeneralSimpleException {
        String personId = BaseCommonUtils.generateUUID();
        PersonManageBean personManageBean = new PersonManageBean();
        boolean isSave = true;
        // 核验证件照，如果证件照存在，则不允许登录
        if(StringUtils.isNotBlank(dto.getCard())){
            List<PersonManageBean> personManageBeanList = this.lambdaQuery().eq(PersonManageBean::getCard, dto.getCard())
                    .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02).list();
            if(CollectionUtils.isNotEmpty(personManageBeanList)){
                throwExceptionCardRepeatRoleInfo(personManageBeanList.get(0).getOrgId());
            }else{
                personManageBeanList = this.lambdaQuery().eq(PersonManageBean::getCard, dto.getCard())
                        .list();
                if(CollectionUtils.isNotEmpty(personManageBeanList)){
                    personId = personManageBeanList.get(0).getObjId();
                    personManageBean.setAccountObjId(personManageBeanList.get(0).getAccountObjId());
                    isSave = false;
                }
            }
        }

        // 校验生日是否符合区间
        String msg = checkPersonAgeLimit(dto.getName(), dto.getBirth());
        if(StringUtils.isNotBlank(msg)){
            throw new GeneralSimpleException("400068", msg);
        }
        
        // 校验培训记录的培训证明
        if(CollectionUtils.isNotEmpty(dto.getTrainingRecordList())){
            List<PersonTrainingRecordSaveDTO> recordSaveDTOList = dto.getTrainingRecordList().stream().filter(obj -> StringUtils.isBlank(obj.getProve())).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(recordSaveDTOList)){
                throw new GeneralSimpleException("400070");
            }
        }
       
        personManageBean.setObjId(personId);
        personManageBean.setCard(dto.getCard());
        personManageBean.setName(dto.getName());
        personManageBean.setSex(dto.getSex());
        personManageBean.setBirth(dto.getBirth());
        personManageBean.setOrgId(dto.getOrgId());
        personManageBean.setType(dto.getType());
        personManageBean.setProfilePicture(dto.getProfilePicture());
        personManageBean.setIfDelete(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
        personManageBean.setHealthCert(dto.getHealthCert());
        
        personManageBean.setId(getPersonId(personManageBean.getCard()));
        
        // 资质证书
        List<PersonCertBean> certBeanList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(dto.getCertList())){
            String finalPersonId = personId;
            dto.getCertList().forEach(cert -> {
                PersonCertBean personCertBean = new PersonCertBean();
                personCertBean.setType(cert.getType());
                personCertBean.setPersonObjId(finalPersonId);
                personCertBean.setIfEnable(cert.getIfEnable());
                if(StringUtils.equals(cert.getIfEnable(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)){
                    personCertBean.setFilePath(cert.getFilePath());
                }
                personCertBean.setObjId(BaseCommonUtils.generateUUID());
                certBeanList.add(personCertBean);
            });
        }
        
        // 培训记录
        List<PersonTrainingRecordBean> trainingRecordBeanList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(dto.getTrainingRecordList())){
            String finalPersonId1 = personId;
            dto.getTrainingRecordList().forEach(trainingRecord -> {
                PersonTrainingRecordBean trainingRecordBean = new PersonTrainingRecordBean();
                trainingRecordBean.setTime(trainingRecord.getTime());
                trainingRecordBean.setContent(trainingRecord.getContent());
                trainingRecordBean.setPersonObjId(finalPersonId1);
                trainingRecordBean.setProve(trainingRecord.getProve());
                
                trainingRecordBean.setObjId(BaseCommonUtils.generateUUID());
                trainingRecordBeanList.add(trainingRecordBean);
            });
        }
        
        // 违章记录
        List<PersonViolationRegulationsRecordBean> violationRegulationsRecordBeanList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(dto.getViolationRegulationsRecordList())){
            String finalPersonId2 = personId;
            dto.getViolationRegulationsRecordList().forEach(violationRegulationsRecord -> {
                PersonViolationRegulationsRecordBean violationRegulationsRecordBean = new PersonViolationRegulationsRecordBean();
                violationRegulationsRecordBean.setTime(violationRegulationsRecord.getTime());
                violationRegulationsRecordBean.setBehavior(violationRegulationsRecord.getBehavior());
                violationRegulationsRecordBean.setPersonObjId(finalPersonId2);
                violationRegulationsRecordBean.setObjId(BaseCommonUtils.generateUUID());
                violationRegulationsRecordBeanList.add(violationRegulationsRecordBean);
            });
        }
        // 用户账号信息
        PersonAccountInfoDTO accountInfo = dto.getAccountInfo();
        if(Objects.nonNull(accountInfo) && StringUtils.isNotBlank(accountInfo.getUserName())){
            personManageBean.setAccountObjId(BaseCommonUtils.generateUUID());
        }
        boolean status = isSave ? save(personManageBean) : updateById(personManageBean);
        if(status){
            // 资质证书
            if(CollectionUtils.isNotEmpty(certBeanList)){
                status = personCertService.saveBatch(certBeanList);
                if(!status){
                    throw new GeneralSimpleException("400034", personManageBean.getName());
                }
            }
            
            // 违章记录
            if(CollectionUtils.isNotEmpty(violationRegulationsRecordBeanList)){
                status = personViolationRegulationsRecordService.saveBatch(violationRegulationsRecordBeanList);
                if(!status){
                    throw new GeneralSimpleException("400035", personManageBean.getName());
                }
            }
            
            // 培训记录
            if(CollectionUtils.isNotEmpty(trainingRecordBeanList)){
                status = personTrainingRecordService.saveBatch(trainingRecordBeanList);
                if(!status){
                    throw new GeneralSimpleException("400036", personManageBean.getName());
                }
            }
            
            if(StringUtils.isNotBlank(personManageBean.getAccountObjId())){
                // 添加账号
                if(isSave || Objects.nonNull(accountInfo)){
                    log.info("人员信息新增：添加账号，用户名：{}", dto.getName());

                    UserSaveDTO userSaveDTO = new UserSaveDTO();
                    BeanUtils.copyProperties(accountInfo, userSaveDTO);
                    status = userService.insertUser(userSaveDTO, personManageBean.getAccountObjId());
                    if(!status){
                        throw new GeneralSimpleException("400047", dto.getName());
                    }
                }else{
                    log.info("人员信息新增：更新账号单位，用户名：{}，单位：{}", dto.getName(), dto.getOrgId());
                    status = userService.updateUserInfoById(dto.getName(), dto.getOrgId(), BaseCodeConstants.CodeType_UserStatus.KEY_UserStatus01, personManageBean.getAccountObjId());
                    if(!status){
                        log.error("人员信息新增：账号更新失败！");
                    }
                }
            }
           
        }

        return personId;
    }

    /**
     * 获取ID
     * @return ID
     */
    @Override
    public Integer getMaxPersonId(){
        Integer id = this.baseMapper.findMaxId();
        if(Objects.isNull(id)){
            id = 1;
        }else{
            id = id + 1;
        }
        return id;
    }

    /**
     * 根据身份证号查询人员ID
     * @param card 身份证号
     * @return 人员ID
     */
    private Integer getPersonId(String card){
        Integer personId = null;
        // 人员数字ID--临时准入人员ID要和人员表保持一致
        if(StringUtils.isNotBlank(card)){
            personId = temporaryAdmissionService.findIdByCard(card);
            if(Objects.nonNull(personId)){
                return personId;
            }
        }

        return getMaxPersonId();
    }
    
    /**
     * 修改人员信息
     *
     * @param dto 人员信息
     * @return 修改状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String updatePerson(PersonManageUpdateDTO dto) throws GeneralSimpleException {
      
        PersonManageBean personManageBean = findById(dto.getObjId());

        // 校验生日是否符合区间
        String msg = checkPersonAgeLimit(dto.getName(), dto.getBirth());
        if(StringUtils.isNotBlank(msg)){
            throw new GeneralSimpleException("400068", msg);
        }

        boolean updateAccount = false;
        boolean responsiblePersonUpdate = false;
        if(!StringUtils.equals(personManageBean.getName(), dto.getName()) || !StringUtils.equals(personManageBean.getOrgId(), dto.getOrgId())){
            updateAccount = true;
            if(!StringUtils.equals(personManageBean.getOrgId(), dto.getOrgId())){
                // 如果单位发生变更，则工程关联的参建单位负责人需要移除
                responsiblePersonUpdate = true;
            }
        }
        // 核验证件照，如果存在重复，则不能添加修改
        if(StringUtils.isNotBlank(dto.getCard())){
            List<PersonManageBean> personManageBeanList = this.lambdaQuery()
                    .eq(PersonManageBean::getCard, dto.getCard())
                    .ne(PersonManageBean::getObjId, dto.getObjId())
                    .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02).list();
            if(CollectionUtils.isNotEmpty(personManageBeanList)){
                throwExceptionCardRepeatRoleInfo(personManageBeanList.get(0).getOrgId());
            }
        }
        
        BeanUtils.copyProperties(dto, personManageBean);
        personManageBean.setIfDelete(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
        boolean status = updateById(personManageBean);
        if(status){
            // 更新账号信息
            if(StringUtils.isNotBlank(personManageBean.getAccountObjId()) && updateAccount){
                userService.updateNameAndOrdIdByAccountId(personManageBean.getName(), personManageBean.getOrgId(), personManageBean.getAccountObjId());    
            }
            
            if (CollectionUtils.isNotEmpty(dto.getCertList())){
                status = personCertService.delByPersonId(dto.getObjId());
                if(status){
                    List<PersonCertBean> certBeanList = Lists.newArrayList();
                    if(CollectionUtils.isNotEmpty(dto.getCertList())){
                        dto.getCertList().forEach(cert -> {
                            PersonCertBean personCertBean = new PersonCertBean();
                            personCertBean.setType(cert.getType());
                            personCertBean.setPersonObjId(personManageBean.getObjId());
                            personCertBean.setIfEnable(cert.getIfEnable());
                            if(StringUtils.equals(cert.getIfEnable(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)){
                                personCertBean.setFilePath(cert.getFilePath());
                            }
                            personCertBean.setObjId(BaseCommonUtils.generateUUID());
                            certBeanList.add(personCertBean);
                        });

                        personCertService.saveBatch(certBeanList);
                    }
                }
            }else{
                status = personCertService.delByPersonId(dto.getObjId());
            }
            
            // 如果单位发生变更，则工程关联的参建单位负责人需要移除
            if(responsiblePersonUpdate){
                constructionWorkService.removeUnitResponsiblePersonByPersonId(personManageBean.getObjId());
            }
        }
        if(status){
            return personManageBean.getObjId();
        }else{
            return null;
        }
    }

    /**
     * 查询用户基本信息
     *
     * @param dto 用户ID
     * @return 用户基本信息
     */
    @Override
    public PersonSimpleInfoVO findById(PersonManageIdDTO dto) throws GeneralSimpleException {
        PersonManageBean personManageBean = findById(dto.getObjId());
        PersonSimpleInfoVO simpleInfoVO = new PersonSimpleInfoVO();
        BeanUtils.copyProperties(personManageBean, simpleInfoVO);
        
        List<PersonCertInfoVO> certInfoVOList = personCertService.findVOByPersonObjId(personManageBean.getObjId());
        simpleInfoVO.setCertList(certInfoVOList);
        
        // 是否黑名单
        boolean ifBlacklist = blacklistService.checkBlackListByIdNumberAndType(personManageBean.getCard(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
        if(ifBlacklist){
            simpleInfoVO.setIfBlacklist(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
        }
        
        // 查询人员账号状态
        if(StringUtils.isNotBlank(simpleInfoVO.getAccountObjId())){
            simpleInfoVO.setStatus(userService.findStatusByUserId(simpleInfoVO.getAccountObjId()));
        }

        return simpleInfoVO;
    }

    /**
     * 分页查询人员信息
     *
     * @param dto 查询条件
     * @return 人员信息
     */
    @Override
    public IPage<PersonPageVO> pageByPersonInfo(PersonManagePageDTO dto) throws GeneralSimpleException {
        return pageByPersonInfo(dto, false);
    }

    /**
     * 分页查询用户信息
     * @param dto 查询条件
     * @param iFBlacklist 黑名单
     * @return 人员信息
     */
    private IPage<PersonPageVO> pageByPersonInfo(PersonManagePageDTO dto, boolean iFBlacklist) throws GeneralSimpleException {
        // -----------------根据权限查询数据---------------------------------
        // 查询权限内的单位
        // 2025-01-22 是否是总部管理员，总部管理员则查询全部
        boolean headOffice = userService.checkHeadOffice();
        boolean adminByUser = userService.checkAdminByUser();
        
        List<String> departmentOrgIdList = orgService.getDataPermissionDepartmentOrgId();
        List<String> participatingUnitOrgIdList;
        if(headOffice){
            participatingUnitOrgIdList = orgService.getAllParticipatingUnitIdByWork();
        }else{
            participatingUnitOrgIdList = orgService.getDataPermissionParticipatingUnitIdByOrgIdIn(departmentOrgIdList);
        }
        List<String> orgIdList = Lists.newArrayList();
        // 准入的人员信息
        List<String> accessPersonIdList = Lists.newArrayList();
        // 部门所属的工程
        List<String> constructionWorkIdList = null;

        // 部门
        if(CollectionUtils.isNotEmpty(departmentOrgIdList)){
            orgIdList.addAll(departmentOrgIdList);
            
            // 是否项目部
            boolean projectDepartment = userService.checkProjectDepartment();
            if(projectDepartment){
                // 根据权限内的部门查询工程信息
                constructionWorkIdList = constructionWorkService.findIdByProjectDepartmentObjIdIn(departmentOrgIdList);
            }else{
                // 非项目部门，则是参建单位，则判断该用户是否是总包单位管理员
                boolean generalContractingUnit = userService.checkGeneralContractingUnit();
                if(generalContractingUnit){
                    // 是总包单位管理员，则总包单位管理员查看的人员信息为：还可以查看其他单位已准入自己所在单位作为总包单位的工程的人员，但不能为其他单位人员“办理准入”
                    constructionWorkIdList = constructionWorkService.findGeneralContractingUnitAccessWorkId();
                    if(CollectionUtils.isNotEmpty(constructionWorkIdList)){
                        participatingUnitOrgIdList = constructionWorkService.findGeneralContractingUnitParticipatingUnitObjIdByObjIdIn(constructionWorkIdList);
                    }else{
                        String orgId = BaseCommonUtils.extractOrdIdByToken();
                        participatingUnitOrgIdList = Lists.newArrayList();
                        participatingUnitOrgIdList.add(orgId);
                    }
                }
            }
        }

        // 参建单位，参建单位不为空，则查询对应的准入人员信息
        // 参建单位为空，说明，当前用户是公司人员但是所属工程未关联参建单位
        if(CollectionUtils.isNotEmpty(participatingUnitOrgIdList)){
            orgIdList.addAll(participatingUnitOrgIdList);

            // 存在参建单位，则查询哪些用户准入了工程
            List<PersonManageBean> personManageBeanList = this.lambdaQuery().in(PersonManageBean::getOrgId, participatingUnitOrgIdList)
                    .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                    .list();
            if(CollectionUtils.isNotEmpty(personManageBeanList)){
                // 参建单位人员信息
                List<String> participatingUnitPersonIdList = personManageBeanList.stream().map(PersonManageBean::getObjId).collect(Collectors.toList());

//                String nowDate = BaseCommonUtils.DATE_FORMAT_DAY_3.format(new Date());
                // 查询准入的工程的人员信息
                List<PersonAccessRelaBean> accessRelaBeanList = personAccessRelaService.lambdaQuery()
                        .in(PersonAccessRelaBean::getPersonId, participatingUnitPersonIdList)
                        .in(CollectionUtils.isNotEmpty(constructionWorkIdList), PersonAccessRelaBean::getConstructionWorkObjId, constructionWorkIdList)
//                        .le(PersonAccessRelaBean::getCycleStart, nowDate)
//                        .ge(PersonAccessRelaBean::getCycleEnd, nowDate)
                        .list();
                if(CollectionUtils.isNotEmpty(accessRelaBeanList)){
                    accessPersonIdList = accessRelaBeanList.stream().map(PersonAccessRelaBean::getPersonId).collect(Collectors.toList());
                }
            }
        }

        if(!headOffice && CollectionUtils.isEmpty(orgIdList)){
            log.info("人员管理：单位信息有误，即不是项目部也不是参建单位");
            return new Page<>(dto.getPage(), dto.getSize());
        }
        
      
        // -----------------end---------------------------------

        IPage<PersonManageBean> personManageBeanIPage = new Page<>(dto.getPage(), dto.getSize());
        
        // 查询黑名单
        List<String> cardList = blacklistService.findIdNumberByType(BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
        cardList = cardList == null ? Lists.newArrayList() : cardList;
        List<String> sourceIdList = Lists.newArrayList();
        if(iFBlacklist){
            sourceIdList = blacklistService.findSourceIdListByType(BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
            if(CollectionUtils.isEmpty(cardList)){
                log.info("人员管理：查询黑名单，黑名单不存在");
                return new Page<>(dto.getPage(), dto.getSize());
            }
            if(CollectionUtils.isEmpty(sourceIdList)){
                sourceIdList.add("error");
            }
        }
        
        // 查询条件中准入工程
        List<String> queryAccessPersonIdList = Lists.newArrayList();
        if(StringUtils.isNotBlank(dto.getConstructionWorkObjId())){
            List<PersonAccessRelaBean> accessRelaBeanList = personAccessRelaService.lambdaQuery().eq(PersonAccessRelaBean::getConstructionWorkObjId, dto.getConstructionWorkObjId()).list();
            if(CollectionUtils.isNotEmpty(accessRelaBeanList)){
                queryAccessPersonIdList = accessRelaBeanList.stream().map(PersonAccessRelaBean::getPersonId).collect(Collectors.toList());
            }
            
            if(CollectionUtils.isEmpty(queryAccessPersonIdList)){
                return new Page<>(dto.getPage(), dto.getSize());
            }
        }

        List<String> finalAccessPersonIdList = accessPersonIdList;
        IPage<PersonManageBean> workBeanIPage = this.lambdaQuery()
                // 查询项目部成员和准入负责的项目的参建单位成员
                .and(!adminByUser && CollectionUtils.isNotEmpty(departmentOrgIdList), 
                        w -> w.in(CollectionUtils.isNotEmpty(departmentOrgIdList), PersonManageBean::getOrgId, departmentOrgIdList)
                                .or()
                                .in(CollectionUtils.isNotEmpty(finalAccessPersonIdList), PersonManageBean::getObjId, finalAccessPersonIdList))
                
                // 如果黑名单存在，则根据黑名单中的card查询人员信息
                .in(iFBlacklist, PersonManageBean::getCard, cardList)
                .in(iFBlacklist, PersonManageBean::getObjId, sourceIdList)
                // 如果黑名单存在，则取消查询删除的人员信息，不存在，则查询未删除的数据
                .eq(!iFBlacklist, PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                
                .eq(StringUtils.isNotEmpty(dto.getType()), PersonManageBean::getType, dto.getType())
                .in(CollectionUtils.isNotEmpty(queryAccessPersonIdList), PersonManageBean::getObjId, queryAccessPersonIdList)
                .eq(StringUtils.isNotEmpty(dto.getOrgId()), PersonManageBean::getOrgId, dto.getOrgId())
                // 人脸照片
                .and(StringUtils.isNotBlank(dto.getIfExistProfilePicture()) && StringUtils.equals(dto.getIfExistProfilePicture(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02), 
                        w -> w.isNull(PersonManageBean::getProfilePicture)
                                .or()
                                .eq(PersonManageBean::getProfilePicture, ""))
                .and(StringUtils.isNotBlank(dto.getIfExistProfilePicture()) && StringUtils.equals(dto.getIfExistProfilePicture(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01), w -> w.isNotNull(PersonManageBean::getProfilePicture).ne(PersonManageBean::getProfilePicture, ""))
                
                .and(StringUtils.isNotEmpty(dto.getSearchStr()),
                        w -> w.like(PersonManageBean::getCard, dto.getSearchStr())
                                .or()
                                .like(PersonManageBean::getName, dto.getSearchStr()))
                .orderByAsc(PersonManageBean::getOrgId)
                .orderByAsc(PersonManageBean::getName)
                .orderByAsc(PersonManageBean::getObjId)
                .page(personManageBeanIPage);

        IPage<PersonPageVO> pageVOIPage = new Page<>(workBeanIPage.getCurrent(), workBeanIPage.getSize(), workBeanIPage.getTotal());
        List<PersonPageVO> pageVOList = Lists.newArrayList();
        // 组装数据
        if(CollectionUtils.isNotEmpty(workBeanIPage.getRecords())) {

            List<String> finalCardList = cardList;
            workBeanIPage.getRecords().forEach(personManage -> {
                PersonPageVO recordVO = new PersonPageVO();
                BeanUtils.copyProperties(personManage, recordVO);

                // 参建单位名称
                if(StringUtils.isNotBlank(personManage.getOrgId())){
                    String orgName = orgService.findOrgNameByOrgId(personManage.getOrgId());
                    recordVO.setOrgName(orgName);
                }

                // 资质证书
                List<PersonCertInfoVO> personCertInfoVOList = personCertService.findVOByPersonObjId(personManage.getObjId());
                if(CollectionUtils.isNotEmpty(personCertInfoVOList)){
                    List<String> certTypeList = personCertInfoVOList.stream()
                            .filter(personCertInfoVO -> StringUtils.equals(personCertInfoVO.getIfEnable(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01))
                            .map(PersonCertInfoVO::getType).distinct().collect(Collectors.toList());
                    recordVO.setCertTypeList(certTypeList);
                }

                // 准入的在建工程
                List<String> personConstructionWorkIdList = personAccessRelaService.lambdaQuery()
                        .eq(PersonAccessRelaBean::getPersonId, personManage.getObjId())
                        .list().stream().map(PersonAccessRelaBean::getConstructionWorkObjId).distinct()
                        .collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(personConstructionWorkIdList)){
                    // 获取交集
//                    List<String> intersection = personConstructionWorkIdList.stream()
//                            .filter(finalConstructionWorkIdList::contains)
//                            .collect(Collectors.toList());
//                    if(CollectionUtils.isNotEmpty(intersection)){
//                        List<String> construnctionWorkNameList = constructionWorkService.findNameByObjIdList(intersection);
//                        recordVO.setWorkNameList(construnctionWorkNameList);
//                    }
                    List<String> construnctionWorkNameList = constructionWorkService.findNameByObjIdList(personConstructionWorkIdList);
                    recordVO.setWorkNameList(construnctionWorkNameList);
                }

                // 校验是否是黑名单
                if(finalCardList.contains(personManage.getCard())){
                    recordVO.setIfBlacklist(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);

                    //加入黑名单原因
                    String reason = blacklistService.findReasonByIdNumberAndType(personManage.getCard(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
                    if(StringUtils.isNotBlank(reason)){
                        recordVO.setReason(reason);
                    }
                }
                
                // 是否存在人脸照片
                if(StringUtils.isNotBlank(personManage.getProfilePicture())){
                    recordVO.setIfExistProfilePicture(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                }else{
                    recordVO.setIfExistProfilePicture(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
                }

                // 单位ID
                recordVO.setOrgId(personManage.getOrgId());
                
                pageVOList.add(recordVO);
            });
            pageVOIPage.setRecords(pageVOList);
        }
        return pageVOIPage;
    }

    /**
     * 删除人员信息
     *
     * @param dto 人员ID
     * @return 删除状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean delByObjId(PersonManageIdDTO dto) throws GeneralSimpleException {
        PersonManageBean personManageBean = findById(dto.getObjId());
        personManageBean.setIfDelete(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
        boolean status = updateById(personManageBean);
        if(status){
            personAccessRelaService.lambdaUpdate().eq(PersonAccessRelaBean::getPersonId, personManageBean.getObjId()).remove();

            if(StringUtils.isNotBlank(personManageBean.getAccountObjId())){
                userService.disable(personManageBean.getAccountObjId());
            }

            // 移除负责人
            constructionWorkService.removeUnitResponsiblePersonByPersonId(personManageBean.getObjId());
        }
        return status; 
    }

    /**
     * 分页查询准入申请
     *
     * @param dto 分页查询
     * @return 准入申请单
     */
    @Override
    public IPage<PersonAccessMonadPageVO> pageByAccessMonad(PersonAccessMonadPageDTO dto) {
        return null;
    }

    /**
     * 加入或取消黑名单
     *
     * @param dto ID信息
     * @return 状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean addBlacklist(PersonManageBlacklistIdDTO dto) throws GeneralSimpleException {
        PersonManageBean personManageBean = findById(dto.getObjId());
        
        if(StringUtils.equals(dto.getIfBlacklist(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)){
            Boolean aBoolean = blacklistService.saveByIdNumberAndTypeAndUserName(personManageBean.getCard(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01, personManageBean.getName(), personManageBean.getObjId(), BaseCodeConstants.CodeType_AddBlackListActionType.KEY_AddBlackListActionType02, dto.getReason());
            if(Objects.nonNull(aBoolean) && aBoolean && StringUtils.isNotBlank(personManageBean.getAccountObjId())){
                // 用户账号添加禁用
                aBoolean = userService.updateStatusByIdAndStatus(BaseCodeConstants.CodeType_UserStatus.KEY_UserStatus02, personManageBean.getAccountObjId(), BaseCodeConstants.CodeType_UserStatus.KEY_UserStatus01);
            }
            return aBoolean;
        }else if(StringUtils.equals(dto.getIfBlacklist(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)){

            // 校验生日是否符合区间
            String msg = checkPersonAgeLimit(personManageBean.getName(), personManageBean.getBirth());
            if(StringUtils.isNotBlank(msg)){
                throw new GeneralSimpleException("400067", msg);
            }

            Boolean aBoolean = blacklistService.delByIdNumberAndType(personManageBean.getCard(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
            if(Objects.nonNull(aBoolean) && aBoolean && StringUtils.isNotBlank(personManageBean.getAccountObjId())){
                // 用户账号解除禁用
                aBoolean = userService.updateStatusByIdAndStatus(BaseCodeConstants.CodeType_UserStatus.KEY_UserStatus01, personManageBean.getAccountObjId(), BaseCodeConstants.CodeType_UserStatus.KEY_UserStatus02);
            }
            return aBoolean;
        }
        return false;
    }

    /**
     * 查询黑名单状态
     *
     * @param associationObjId 用户ID
     * @return 状态
     */
    @Override
    public boolean checkBlackList(String associationObjId) throws GeneralSimpleException {
        PersonManageBean personManageBean = findById(associationObjId);
        return blacklistService.checkBlackListByIdNumberAndType(personManageBean.getCard(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
    }

    /**
     * 分页查询人员信息-黑名单
     *
     * @param dto 分页查询条件
     * @return 人员信息
     */
    @Override
    public IPage<PersonPageVO> pageByPersonInfoBlacklist(PersonManagePageDTO dto) throws GeneralSimpleException {
        return pageByPersonInfo(dto, true);
    }

    /**
     * 根据身份证号查询用户信息
     *
     * @param dto 身份证号
     * @return 用户信息
     */
    @Override
    public PersonSimpleInfoCardVO findByCard(PersonManageCardDTO dto) throws GeneralSimpleException {
        PersonSimpleInfoCardVO simpleInfoCardVO = new PersonSimpleInfoCardVO();
        
        List<PersonManageBean> personManageBeanList = this.lambdaQuery().eq(PersonManageBean::getCard, dto.getCard())
                .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .list();
        if(CollectionUtils.isNotEmpty(personManageBeanList)){
            PersonManageBean personManageBean = personManageBeanList.get(0);
            // 如果当前人员信息符合当前用户权限范围内，则返回用户信息，否则不给查看

            // -----------------根据权限查询数据---------------------------------
            // 查询权限内的单位
            String orgId = BaseCommonUtils.extractOrdIdByToken();
            if(StringUtils.isBlank(orgId)){
                log.info("单位信息不存在");
                throw new GeneralSimpleException("100003");
            }
            // 是否查询全部
            boolean headOffice = userService.checkHeadOffice();
            List<String> orgIdList = null;
            if(!headOffice){
                orgIdList = orgService.getDataPermissionOrgId();
            }
            // -----------------end---------------------------------          
          
            // 当前用户不是系统管理员和总部管理员，则判断是否有权限查看当前用户信息
            if(!headOffice && !orgIdList.contains(personManageBean.getOrgId())){
                // 身份证号对应的用户和当前登录用户不是同一个单位范围，不允许查看
                throwExceptionCardRepeatRoleInfo(personManageBean.getOrgId());
            }
            
            BeanUtils.copyProperties(personManageBean, simpleInfoCardVO);

            List<PersonCertInfoVO> certInfoVOList = personCertService.findVOByPersonObjId(personManageBean.getObjId());
            simpleInfoCardVO.setCertList(certInfoVOList);
        }else{
            personManageBeanList = this.lambdaQuery().eq(PersonManageBean::getCard, dto.getCard())
                    .orderByDesc(PersonManageBean::getCreateTime)
                    .orderByDesc(PersonManageBean::getObjId)
                    .list();
            if(CollectionUtils.isNotEmpty(personManageBeanList)){
                PersonManageBean personManageBean = personManageBeanList.get(0);
                BeanUtils.copyProperties(personManageBean, simpleInfoCardVO);
                simpleInfoCardVO.setOrgId(null);
            }
        }

        // 查询资质证书
        if(StringUtils.isNotBlank(simpleInfoCardVO.getObjId())){
            List<PersonCertInfoVO> certInfoVOList = personCertService.findVOByPersonObjId(simpleInfoCardVO.getObjId());
            simpleInfoCardVO.setCertList(certInfoVOList);

            // 查询人员账号状态
            if(StringUtils.isNotBlank(simpleInfoCardVO.getAccountObjId())){
                simpleInfoCardVO.setStatus(userService.findStatusByUserId(simpleInfoCardVO.getAccountObjId()));
            }
        }

        boolean ifBlackList = blacklistService.checkBlackListByIdNumberAndType(dto.getCard(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
        if(ifBlackList){
            simpleInfoCardVO.setIfBlacklist(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
            simpleInfoCardVO.setCard(dto.getCard());
        }
        
        // 查询账号状态
        if(StringUtils.isNotBlank(simpleInfoCardVO.getAccountObjId())){
            UserBaseInfoVO userBaseInfoVO = userService.findById(simpleInfoCardVO.getAccountObjId());
            if(Objects.nonNull(userBaseInfoVO)){
                simpleInfoCardVO.setStatus(userBaseInfoVO.getStatus());
            }
        }
        return simpleInfoCardVO;
    }

    /**
     * 抛异常-证件照重复角色信息
     * @param personOrgId 人员单位
     * @throws GeneralSimpleException 异常信息
     */
    private void throwExceptionCardRepeatRoleInfo(String personOrgId) throws GeneralSimpleException {
        OrgBaseInfoVO orgBaseInfoVO = orgService.findById(new OrgIdRequestDTO(personOrgId));
        String orgName = "";
        if(Objects.nonNull(orgBaseInfoVO)){
            orgName = orgBaseInfoVO.getName();
            if(StringUtils.isNotBlank(orgBaseInfoVO.getPid())){
                orgBaseInfoVO = orgService.findById(new OrgIdRequestDTO(orgBaseInfoVO.getPid()));
                if(Objects.nonNull(orgBaseInfoVO)){
                    orgName = orgBaseInfoVO.getName() + "-" + orgName;
                }
            }
        }else{
            // 参建单位
            if(StringUtils.isNotBlank(personOrgId)){
                String name = participatingUnitService.findNameByObjId(personOrgId);
                if(StringUtils.isNotBlank(name)){
                    orgName = "参建单位-" + name;
                }
            }
        }

        if(StringUtils.isBlank(orgName)){
            orgName = "单位信息不存在";
        }

        throw new GeneralSimpleException("400045", orgName);
    }

    /**
     * 解除黑名单
     *
     * @param dto 用户信息
     * @return 解除状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean liftBlacklist(PersonManageIdDTO dto) throws GeneralSimpleException {
        PersonManageBean personManageBean = findById(dto.getObjId());

        // 校验生日是否符合区间
        String msg = checkPersonAgeLimit(personManageBean.getName(), personManageBean.getBirth());
        if(StringUtils.isNotBlank(msg)){
            throw new GeneralSimpleException("400067", msg);
        }

        Boolean aBoolean = blacklistService.delByIdNumberAndType(personManageBean.getCard(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
        if(Objects.nonNull(aBoolean) && aBoolean && StringUtils.isNotBlank(personManageBean.getAccountObjId())){
            // 用户账号解除禁用
            aBoolean = userService.updateStatusByIdAndStatus(BaseCodeConstants.CodeType_UserStatus.KEY_UserStatus01, personManageBean.getAccountObjId(), BaseCodeConstants.CodeType_UserStatus.KEY_UserStatus02);
        }

        return aBoolean;
    }

    /**
     * 校验生日是否符合区间
     * @param name 人员姓名
     * @param birth 人员生日
     * @return 返回文字说明
     */
    private String checkPersonAgeLimit(String name, Date birth){
        String msg = "";
        if(Objects.nonNull(birth)){
            LocalDate currentDate = LocalDate.now(); // 当前日期
            // 将 Date 转换为 LocalDate
            LocalDate localDate = birth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            // 计算年龄
            int age = Period.between(localDate, currentDate).getYears();

            // 判断年龄是否超过60岁或小于18岁
            if (age >= blacklistAgeLevel) {
                msg = String.format("人员%s的年龄已经超过了%s岁", name, blacklistAgeLevel);
            } else if (age < 18) {
                msg = String.format("人员%s未成年", name);
            }
        }
        return msg;
    }

    /**
     * 保存准入工程
     *
     * @param personId              人员ID
     * @param constructionWorkObjId 工程ID
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveAccessWork(String personId, String constructionWorkObjId, Date cycleStart, Date cycleEnd, String accessMonadObjId) {
        PersonManageBean personManageBean = this.getById(personId);
        if(Objects.nonNull(personManageBean)){
            PersonAccessRelaBean accessRelaBean = new PersonAccessRelaBean();
            accessRelaBean.setObjId(BaseCommonUtils.generateUUID());
            accessRelaBean.setPersonId(personId);
            accessRelaBean.setConstructionWorkObjId(constructionWorkObjId);
            accessRelaBean.setCycleStart(cycleStart);
            accessRelaBean.setCycleEnd(cycleEnd);
            accessRelaBean.setAccessMonadObjId(accessMonadObjId);
            boolean status = personAccessRelaService.save(accessRelaBean);
            
            if(status){
                CompletableFuture.runAsync(() -> barrierGateService.issuingPersonByPersonObjIdAndDepartment(personManageBean.getObjId()));
            }
        }
    }

    /**
     * 新增人员账号
     *
     * @param dto 账号新增
     * @return 新增状态
     */
    @Override
    public boolean insertAccount(PersonAccountSaveDTO dto) throws GeneralSimpleException {
        PersonManageBean personManageBean = findById(dto.getPersonId());
        if(StringUtils.isNotBlank(personManageBean.getCard())){
            boolean status = blacklistService.checkBlackListByIdNumberAndType(personManageBean.getCard(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
            if(status){
                throw new GeneralSimpleException("400048");
            }
        }
        
        personManageBean.setAccountObjId(BaseCommonUtils.generateUUID());

        boolean status = updateById(personManageBean);
        if(status){
            log.info("人员信息新增：添加账号，用户名：{}", personManageBean.getName());

            UserSaveDTO userSaveDTO = new UserSaveDTO();
            BeanUtils.copyProperties(dto, userSaveDTO);
            status = userService.insertUser(userSaveDTO, personManageBean.getAccountObjId());
            if(!status){
                throw new GeneralSimpleException("400047", personManageBean.getName());
            }
        }
        return status;
    }

    /**
     * 分页查询证件列表
     *
     * @param dto 查询条件
     * @return 证件列表
     */
    @Override
    public IPage<CertificatePageVO> pageCertByPersonAndCar(CertificatePageDTO dto) throws GeneralSimpleException {
        int page = dto.getPage();
        if(page >= 1){
            page --;
        }
        
        int size = dto.getSize();
        int index = page * size;

        boolean headOffice = userService.checkHeadOffice();
        List<String> dataPermissionOrgId = Lists.newArrayList();
        if(!headOffice){
            dataPermissionOrgId = orgService.getDataPermissionOrgId();
            if(CollectionUtils.isEmpty(dataPermissionOrgId)){
                return new Page<>(dto.getPage(), dto.getSize());
            }
        }

        // 连表查询证件照
        List<CertificatePageVO> pageVOList = this.baseMapper.pageCertByPersonAndCar(dto.getSearchStr(), dataPermissionOrgId, index, size);
        pageVOList = pageVOList == null ? Lists.newArrayList() : pageVOList;
        
        int count = this.baseMapper.countCertByPersonAndCar(dto.getSearchStr(), dataPermissionOrgId);
        IPage<CertificatePageVO> pageVOIPage = new Page<>(pageVOList.size(), dto.getSize(), count);
        if(CollectionUtils.isNotEmpty(pageVOList)){

            List<String> carIdList = pageVOList.stream().filter(obj -> StringUtils.equals(obj.getType(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType02))
                    .map(CertificatePageVO::getObjId).collect(Collectors.toList());
            Map<String, String> documentMap;
            Map<String, Map<String, String>> carImageMap = Maps.newHashMap();
            if(CollectionUtils.isNotEmpty(carIdList)){
                List<VehicleInfoBean> vehicleInfoBeanList = vehicleService.lambdaQuery()
                        .in(VehicleInfoBean::getObjId, carIdList)
                        .isNotNull(VehicleInfoBean::getDocument)
                        .ne(VehicleInfoBean::getDocument, "")
                        .list();
                if(CollectionUtils.isNotEmpty(vehicleInfoBeanList)){
                    documentMap = vehicleInfoBeanList.stream().collect(Collectors.toMap(VehicleInfoBean::getObjId, VehicleInfoBean::getDocument));
                    documentMap.forEach((k, v) -> {
                        List<String> documentList = Arrays.asList(v.split(",", -1));
                        Map<String, String> imageIdMap = attachmentService.findImageIdByImageIdIn(documentList);
                        if(Objects.nonNull(imageIdMap)){
                            carImageMap.put(k, imageIdMap);
                        }
                    });
                }
            }

            List<CodeVO> qualificationCertificateTypeList = codeService.findByTypeList(Collections.singletonList(BaseCodeConstants.CodeType_05.KEY_QualificationCertificateType));

            Map<String, String> qualificationCertificateTypeMap = Maps.newHashMap();
            if(CollectionUtils.isNotEmpty(qualificationCertificateTypeList)){
                qualificationCertificateTypeMap = qualificationCertificateTypeList.stream().collect(Collectors.toMap(CodeVO::getKey, CodeVO::getName));
            }

            Map<String, String> finalQualificationCertificateTypeMap = qualificationCertificateTypeMap;
            pageVOList.forEach(pageVO -> {
                // 单位名称
                pageVO.setOrgName(orgService.findOrgNameByOrgId(pageVO.getOrgId()));

                pageVO.setCarType(pageVO.getCarType());
                
                // 是否黑名单
                boolean status = blacklistService.checkBlackListByIdNumberAndType(pageVO.getCredentialNo(), pageVO.getType());
                if(status){
                    pageVO.setIfBlacklist(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                }
                
                // 证书
                List<CertificateDetailListVO> certList = Lists.newArrayList();
                if(StringUtils.equals(pageVO.getType(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01)){
                    // 人员
                    List<PersonCertInfoVO> personCertInfoVOList = personCertService.findVOByPersonObjId(pageVO.getObjId());
                    if(CollectionUtils.isNotEmpty(personCertInfoVOList)){
                        personCertInfoVOList.forEach(personCertInfoVO -> {
                            CertificateDetailListVO detailListVO = new CertificateDetailListVO();
                            detailListVO.setFileId(personCertInfoVO.getFilePath());
                            detailListVO.setTypeName(finalQualificationCertificateTypeMap.get(personCertInfoVO.getType()));
                            detailListVO.setFileName(personCertInfoVO.getFileName());
                            detailListVO.setType(personCertInfoVO.getType());
                            certList.add(detailListVO);
                        });
                        pageVO.setCertList(certList);
                    }
                    
                    // 计算年龄
                    // 将java.util.Date转换为java.time.LocalDate
                    if(Objects.nonNull(pageVO.getBirth())){
                        LocalDate localDate = pageVO.getBirth().toInstant()
                                .atZone(ZoneId.systemDefault())
                                .toLocalDate();

                        LocalDate currentDate = LocalDate.now();
                        Period age = Period.between(localDate, currentDate);
                        pageVO.setAge(String.valueOf(age.getYears()));
                        if(StringUtils.isNotBlank(pageVO.getAge())){
                            pageVO.setAge(pageVO.getAge() + "岁");
                        }
                    }
                   
                }else if(StringUtils.equals(pageVO.getType(), BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType02)){
                    // 车辆
                    if(carImageMap.containsKey(pageVO.getObjId())){
                        Map<String, String> imageIdMap = carImageMap.get(pageVO.getObjId());
                        imageIdMap.forEach((k, v) -> {
                            CertificateDetailListVO detailListVO = new CertificateDetailListVO();
                            detailListVO.setFileId(k);
                            detailListVO.setFileName(v);
                            certList.add(detailListVO);
                        });
                        pageVO.setCertList(certList);
                    }
                }
            });
            pageVOIPage.setRecords(pageVOList);
        }
        
        return pageVOIPage;
    }

    /**
     * 查询人员树
     *
     * @param dto 查询条件
     * @return 人员树
     */
    @Override
    public List<OrgPersonInfoVO> treeByPerson(PersonManageTreeDTO dto) {
        List<OrgPersonInfoVO> allPersonInfoVOList = Lists.newArrayList();
        // 所有人员信息
        List<PersonManageBean> personManageBeanList = this.lambdaQuery()
                .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .like(StringUtils.isNotEmpty(dto.getPersonName()), PersonManageBean::getName, dto.getPersonName())
                .list();
        if(CollectionUtils.isEmpty(personManageBeanList)){
            log.info("人员信息不存在，不显示树形菜单");
            return Lists.newArrayList();
        }
        Map<String, List<PersonManageBean>> personOrgMap = personManageBeanList.stream().collect(Collectors.groupingBy(PersonManageBean::getOrgId));
        // 用户所有的单位ID
        List<String> personAllOrgIdSet = Lists.newArrayList();
        personAllOrgIdSet.addAll(personOrgMap.keySet());
        
        // 所有单位
        List<OrgBean> orgBeanList = orgService.lambdaQuery().list();
        orgBeanList = orgBeanList == null ? Lists.newArrayList() : orgBeanList;
        Map<String, List<OrgBean>> orgBeanMap = orgBeanList.stream().collect(Collectors.groupingBy(OrgBean::getId));

        // 组装用户单位信息
        List<OrgBean> userOrgBeanList = orgBeanList.stream().filter(obj -> personAllOrgIdSet.contains(obj.getId())).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(userOrgBeanList)){
            List<OrgPersonInfoVO> departmentInfoVOList = Lists.newArrayList();
            userOrgBeanList.parallelStream().forEach(userOrgBean -> {
                OrgPersonInfoVO orgPersonInfoVO = new OrgPersonInfoVO();
                BeanUtils.copyProperties(userOrgBean, orgPersonInfoVO);
                orgPersonInfoVO.setObjId(userOrgBean.getId());
                
                if(personOrgMap.containsKey(userOrgBean.getId())){
                    List<PersonManageBean> personManageBeans = personOrgMap.get(userOrgBean.getId());
                    List<OrgPersonInfoVO> userInfoVOList = Lists.newArrayList();
                    personManageBeans.forEach(personManageBean -> {
                        OrgPersonInfoVO userPersonInfoVO = new OrgPersonInfoVO();
                        userPersonInfoVO.setObjId(personManageBean.getObjId());
                        userPersonInfoVO.setPid(userOrgBean.getId());
                        userPersonInfoVO.setName(personManageBean.getName());
                        userPersonInfoVO.setCreateTime(personManageBean.getCreateTime());
                        userPersonInfoVO.setIfPerson(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                        userInfoVOList.add(userPersonInfoVO);
                    });
                    orgPersonInfoVO.setChildrenList(userInfoVOList);
                }
                
                departmentInfoVOList.add(orgPersonInfoVO);
            });

            // 组装数据
            List<OrgPersonInfoVO> personInfoVOList = assembleChildrenOrgPersonInfoVO(orgBeanMap, personAllOrgIdSet, departmentInfoVOList);
            if(CollectionUtils.isNotEmpty(personInfoVOList)){
                allPersonInfoVOList.addAll(personInfoVOList);
            }
        }
        

        // 所有参建单位
        List<ParticipatingUnitBean> participatingUnitBeanList = participatingUnitService
                .lambdaQuery()
                .in(ParticipatingUnitBean::getObjId, personAllOrgIdSet)
                .orderByDesc(ParticipatingUnitBean::getCreateTime)
                .orderByDesc(ParticipatingUnitBean::getUnitName)
                .orderByDesc(ParticipatingUnitBean::getObjId)
                .list();
        // 组装所属参建单位树
        if(CollectionUtils.isNotEmpty(participatingUnitBeanList)){
            List<OrgPersonInfoVO> participatingUnitInfoVOList = Lists.newArrayList();
            OrgPersonInfoVO orgPersonInfoVO = new OrgPersonInfoVO();
            orgPersonInfoVO.setName(participatingUnitTreeName);
            orgPersonInfoVO.setObjId(participatingUnitTreeId);
            
            participatingUnitBeanList.forEach(participatingUnitBean -> {
                OrgPersonInfoVO tempInfoVO = new OrgPersonInfoVO();
                tempInfoVO.setName(participatingUnitBean.getUnitName());
                tempInfoVO.setObjId(participatingUnitBean.getObjId());

                if(personOrgMap.containsKey(participatingUnitBean.getObjId())){
                    List<PersonManageBean> personManageBeans = personOrgMap.get(participatingUnitBean.getObjId());
                    List<OrgPersonInfoVO> userInfoVOList = Lists.newArrayList();
                    personManageBeans.forEach(personManageBean -> {
                        OrgPersonInfoVO userPersonInfoVO = new OrgPersonInfoVO();
                        userPersonInfoVO.setObjId(personManageBean.getObjId());
                        userPersonInfoVO.setPid(participatingUnitBean.getObjId());
                        userPersonInfoVO.setName(personManageBean.getName());
                        userPersonInfoVO.setCreateTime(personManageBean.getCreateTime());
                        userPersonInfoVO.setIfPerson(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01);
                        userInfoVOList.add(userPersonInfoVO);
                    });
                    orgPersonInfoVO.setChildrenList(userInfoVOList);
                }
                
                participatingUnitInfoVOList.add(tempInfoVO);
            });
            orgPersonInfoVO.setChildrenList(participatingUnitInfoVOList);
            allPersonInfoVOList.add(orgPersonInfoVO);
        }
        return allPersonInfoVOList;
    }

    /**
     * 查询人员名称
     *
     * @param objId 人员ID
     */
    @Override
    public String findNameByObjId(String objId) {
        PersonManageBean personManageBean = this.lambdaQuery().eq(PersonManageBean::getObjId, objId).one();
        if(Objects.nonNull(personManageBean)){
            return personManageBean.getName();
        }
        return null;
    }

    /**
     * 删除人员账号
     *
     * @param accountObjId 账号ID
     * @return 删除状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean delAccount(String accountObjId) {
        List<PersonManageBean> personManageBeanList = this.lambdaQuery().eq(PersonManageBean::getAccountObjId, accountObjId).list();
        if(CollectionUtils.isNotEmpty(personManageBeanList)){
            personManageBeanList.forEach(personManageBean -> {
                personManageBean.setAccountObjId(null);
            });
            
            updateBatchById(personManageBeanList);
        }
        return false;
    }

    /**
     * 根据参建单位和工程查询准入的用户名称
     *
     * @param constructionWorkObjId  工程ID
     * @param participatingUnitObjId 参建单位ID
     * @return 准入人员名称
     */
    @Override
    public List<String> findAccessPersonNameByWorkObjIdAndUnitObjId(String constructionWorkObjId, String participatingUnitObjId) {
        String nowDate = BaseCommonUtils.DATE_FORMAT_DAY_3.format(new Date());
        return this.baseMapper.findAccessPersonNameByWorkObjIdAndUnitObjId(constructionWorkObjId, participatingUnitObjId, nowDate);
    }

    /**
     * 更新用户准入周期
     *
     * @param constructionWorkObjId  工程ID
     * @param participatingUnitObjId 参建单位ID
     * @return 更新状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean updateAccessCycleByWorkObjIdAndUnitObjId(String constructionWorkObjId, String participatingUnitObjId) {
        
        // 准入周期还没开始的，则删除准入
        personAccessRelaService.delAccessByWorkObjIdAndUnitObjIdAndCycleStartGt(constructionWorkObjId, participatingUnitObjId, BaseCommonUtils.DATE_FORMAT_DAY_3.format(new Date()));
        
        // 正在准入，则更新准入时间
        personAccessRelaService.updateAccessCycleEndByWorkObjIdAndUnitObjIdAndCycleStartGtAndCycleEndLt(constructionWorkObjId, participatingUnitObjId, BaseCommonUtils.DATE_FORMAT_DAY_3.format(new Date()));
        
        return true;
    }

    /**
     * 根据单位锁定用户账号
     *
     * @param orgId 单位ID
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void lockPersonAccountByOrgId(String orgId) {

        List<PersonManageBean> personManageBeanList = this.lambdaQuery().eq(PersonManageBean::getOrgId, orgId).list();
        if(CollectionUtils.isNotEmpty(personManageBeanList)){
            List<String> personAccountIdList = personManageBeanList.stream().map(PersonManageBean::getAccountObjId).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(personAccountIdList)){
                userService.disable(personAccountIdList);
            }
        }
    }

    /**
     * 根据人员姓名查询证件信息
     *
     * @param dto 姓名
     * @return 人员账号信息
     */
    @Override
    public List<PersonCardInfoVO> findByName(PersonManageNameDTO dto) throws GeneralSimpleException {
        // 总部管理员
        boolean headOffice = userService.checkHeadOffice();
        // 系统管理员
        boolean admin = userService.checkAdminByUser();
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        
        String workId = "";
        if(StringUtils.isNotBlank(dto.getPendingViolationHandlingObjId())){
            SilentResultBean silentResultBean = silentResultService.getById(dto.getPendingViolationHandlingObjId());
            if(Objects.nonNull(silentResultBean)){
                workId = silentResultBean.getConstructionWorkObjId();
            }else{
                throw new GeneralSimpleException("400072");
            }
        }
        
        List<String> orgIdList = Lists.newArrayList();
        if(!headOffice && !admin){
            // 根据单位查询监理单位所监理的工程，查询工程下的所有参建单位
            List<String> participatingUnitObjIdList = constructionWorkService.findParticipatingUnitObjIdBySupervisorUnit(orgId, workId);
            if(CollectionUtils.isNotEmpty(participatingUnitObjIdList)){
                orgIdList = participatingUnitObjIdList;
            }else{
                orgIdList = orgService.getDataPermissionOrgId();    
            }
        }
        
        List<PersonManageBean> personManageBeanList = this.lambdaQuery()
                .in(!headOffice && !admin, PersonManageBean::getOrgId, orgIdList)
                .like(PersonManageBean::getName, dto.getName())
                .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .orderByAsc(PersonManageBean::getCard)
                .orderByAsc(PersonManageBean::getObjId)
                .list();
        List<PersonCardInfoVO> cardInfoVOList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(personManageBeanList)){
            personManageBeanList.forEach(personManageBean -> {
                PersonCardInfoVO cardInfoVO = new PersonCardInfoVO();
                cardInfoVO.setObjId(personManageBean.getObjId());
                cardInfoVO.setName(personManageBean.getName());
                cardInfoVO.setCard(personManageBean.getCard());
                cardInfoVO.setOrgId(personManageBean.getOrgId());
                cardInfoVO.setType(personManageBean.getType());
                if(StringUtils.isNotBlank(personManageBean.getOrgId())){
                    cardInfoVO.setOrgName(orgService.findOrgNameByOrgId(personManageBean.getOrgId()));
                }

                cardInfoVOList.add(cardInfoVO);
            });
        }
        return cardInfoVOList;
    }

    /**
     * 根据用户ID查询用户详细信息
     *
     * @param personIdList 用户ID
     * @param workId 工程ID
     * @return 用户详细信息
     */
    @Override
    public List<PersonSyncDetailInfoVO> findByPersonIdInAndWorkId(List<String> personIdList, String workId) {

        // 项目部
        List<PersonSyncDetailInfoVO> detailInfoVOList =  department(personIdList, workId);
        if(CollectionUtils.isNotEmpty(detailInfoVOList)){
            List<String> collect = detailInfoVOList.stream().map(PersonSyncDetailInfoVO::getPerson_id).collect(Collectors.toList());
            personIdList.removeAll(collect);

            if(CollectionUtils.isNotEmpty(personIdList)){
                // 参建单位
                detailInfoVOList.addAll(participatingUnit(personIdList, workId));
            }
        }else{
            // 参建单位
            detailInfoVOList =  participatingUnit(personIdList, workId);
        }

        return detailInfoVOList;
    }

    /**
     * 参建单位人员信息--人员道闸使用
     * @param personIdList 人员列表
     * @param workId 工程ID
     * @return 参建单位人员信息
     */
    private List<PersonSyncDetailInfoVO> participatingUnit(List<String> personIdList, String workId) {

        List<PersonManageBean> personManageBeanList = this.lambdaQuery()
                .in(PersonManageBean::getId, personIdList)
                .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .list();
        List<PersonSyncDetailInfoVO> detailInfoVOList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(personManageBeanList)){
            List<String> cardList = personManageBeanList.stream().map(PersonManageBean::getCard).collect(Collectors.toList());
            List<String> personObjIdList = personManageBeanList.stream().map(PersonManageBean::getObjId).collect(Collectors.toList());

            List<String> blacklistPersonIdList = blacklistService.findBlacklistByIdNumberInAndType(cardList, BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
            blacklistPersonIdList = blacklistPersonIdList == null ? Lists.newArrayList() : blacklistPersonIdList;
            List<String> finalBlacklistPersonIdList = blacklistPersonIdList;

            List<PersonAccessRelaBean> personAccessRelaBeanList = personAccessRelaService.findAccessInfoByPersonIdInAndCycleEndGeAndWorkId(personObjIdList, DateUtil.endOfDay(new Date()), workId);
            Map<String, List<PersonAccessRelaBean>> accessRelaMap = Maps.newHashMap();
            if(CollectionUtils.isNotEmpty(personAccessRelaBeanList)){
                accessRelaMap = personAccessRelaBeanList.stream().collect(Collectors.groupingBy(PersonAccessRelaBean::getPersonId));

                personManageBeanList = this.lambdaQuery()
                        .in(PersonManageBean::getObjId, accessRelaMap.keySet())
                        .list();
            }

            Map<String, List<PersonAccessRelaBean>> finalAccessRelaMap = accessRelaMap;
            personManageBeanList.forEach(personManageBean -> {
                PersonSyncDetailInfoVO detailInfoVO = new PersonSyncDetailInfoVO();
                detailInfoVO.setPerson_id(String.valueOf(personManageBean.getId()));
                detailInfoVO.setId_card(personManageBean.getCard());
                detailInfoVO.setPerson_name(personManageBean.getName());

                detailInfoVO.setPerson_type(finalBlacklistPersonIdList.contains(personManageBean.getCard()) ? MqttEnum.PersonType.BLACKLIST.getKey() : MqttEnum.PersonType.WHITE_LIST.getKey());

                // 性别
                int sex = 0;
                if(StringUtils.isNotBlank(personManageBean.getSex())){
                    sex = Integer.parseInt(personManageBean.getSex());
                }
                detailInfoVO.setSex(sex);

                // 生日
                if(Objects.nonNull(personManageBean.getBirth())){
                    detailInfoVO.setBirthday(BaseCommonUtils.DATE_FORMAT_DAY_3.format(personManageBean.getBirth()));
                }
                if(StringUtils.isNotBlank(personManageBean.getProfilePicture())){
                    detailInfoVO.setTemplateImgUrl(Collections.singletonList(attachmentService.findStaticImagePath(personManageBean.getProfilePicture())));
                }
                boolean status = orgService.checkParticipatingUnitByOrgId(personManageBean.getOrgId());
                if(status){
                    // 准入期限
                    if(finalAccessRelaMap.containsKey(personManageBean.getObjId())){
                        List<PersonAccessRelaBean> personAccessRelaBeans = finalAccessRelaMap.get(personManageBean.getObjId());
                        PersonAccessRelaBean accessRelaBean = personAccessRelaBeans.get(0);
                        if(Objects.nonNull(accessRelaBean.getCycleStart())){
                            Date cycleStart = accessRelaBean.getCycleStart();
                            String dateStr = BaseCommonUtils.DATE_FORMAT_DAY_3.format(cycleStart);
                            String timeStr = BaseCommonUtils.DATE_FORMAT_HOUR_MI_SECOND.format(cycleStart);
                            detailInfoVO.setThroughDateFrom(dateStr + " ");
                            detailInfoVO.setThroughMomentFrom(timeStr);
                        }

                        if(Objects.nonNull(accessRelaBean.getCycleEnd())){
                            Date cycleEnd = accessRelaBean.getCycleEnd();
                            String dateStr = BaseCommonUtils.DATE_FORMAT_DAY_3.format(cycleEnd);
                            String timeStr = BaseCommonUtils.DATE_FORMAT_HOUR_MI_SECOND.format(cycleEnd);
                            detailInfoVO.setThroughDateTo(dateStr + " ");
                            detailInfoVO.setThroughMomentTo(timeStr);
                        }
                    }else{
                        return;
                    }
                }else{
                    return;
                }

                detailInfoVOList.add(detailInfoVO);
            });
        }

        return detailInfoVOList;
    }

    /**
     * 项目部人员信息--人员道闸使用
     * @param personIdList 人员列表
     * @param workId 工程ID
     * @return 项目部人员信息
     */
    private List<PersonSyncDetailInfoVO> department(List<String> personIdList, String workId){
        String projectDepartmentObjIdByObjId = constructionWorkService.findProjectDepartmentObjIdByObjId(workId);
        if(StringUtils.isEmpty(projectDepartmentObjIdByObjId)){
            return Lists.newArrayList();
        }
        List<PersonManageBean> personManageBeanList = this.lambdaQuery()
                .in(PersonManageBean::getId, personIdList)
                .eq(PersonManageBean::getOrgId, projectDepartmentObjIdByObjId)
                .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .list();
        List<PersonSyncDetailInfoVO> detailInfoVOList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(personManageBeanList)){
            List<String> cardList = personManageBeanList.stream().map(PersonManageBean::getCard).collect(Collectors.toList());

            List<String> blacklistPersonIdList = blacklistService.findBlacklistByIdNumberInAndType(cardList, BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01);
            blacklistPersonIdList = blacklistPersonIdList == null ? Lists.newArrayList() : blacklistPersonIdList;
            List<String> finalBlacklistPersonIdList = blacklistPersonIdList;

            personManageBeanList.forEach(personManageBean -> {
                PersonSyncDetailInfoVO detailInfoVO = new PersonSyncDetailInfoVO();
                detailInfoVO.setPerson_id(String.valueOf(personManageBean.getId()));
                detailInfoVO.setId_card(personManageBean.getCard());
                detailInfoVO.setPerson_name(personManageBean.getName());

                detailInfoVO.setPerson_type(finalBlacklistPersonIdList.contains(personManageBean.getCard()) ? MqttEnum.PersonType.BLACKLIST.getKey() : MqttEnum.PersonType.WHITE_LIST.getKey());

                // 性别
                int sex = 0;
                if(StringUtils.isNotBlank(personManageBean.getSex())){
                    sex = Integer.parseInt(personManageBean.getSex());
                }
                detailInfoVO.setSex(sex);

                // 生日
                if(Objects.nonNull(personManageBean.getBirth())){
                    detailInfoVO.setBirthday(BaseCommonUtils.DATE_FORMAT_DAY_3.format(personManageBean.getBirth()));
                }
                if(StringUtils.isNotBlank(personManageBean.getProfilePicture())){
                    detailInfoVO.setTemplateImgUrl(Collections.singletonList(attachmentService.findStaticImagePath(personManageBean.getProfilePicture())));
                }
                boolean status = orgService.checkDepartmentByOrgId(personManageBean.getOrgId());
                if(status){
                    detailInfoVO.setThroughDateFrom(Constants.CYCLE_START_DATE_INIT);
                    detailInfoVO.setThroughMomentFrom(Constants.CYCLE_START_TIME_INIT);

                    detailInfoVO.setThroughDateTo(Constants.CYCLE_END_DATE_INIT);
                    detailInfoVO.setThroughMomentTo(Constants.CYCLE_END_TIME_INIT);
                }else{
                    return;
                }

                detailInfoVOList.add(detailInfoVO);
            });
        }

        return detailInfoVOList;
    }

    /**
     * 根据用户ID查询用户信息
     *
     * @param id 用户ID
     */
    @Override
    public PersonSimpleInfoVO findById(int id) {
        PersonSimpleInfoVO personSimpleInfoVO = new PersonSimpleInfoVO();
        PersonManageBean personManageBean = this.lambdaQuery().eq(PersonManageBean::getId, id).last(Constants.LAST_SQL).one();
        if(Objects.nonNull(personManageBean)){
            BeanUtils.copyProperties(personManageBean, personSimpleInfoVO);
            return personSimpleInfoVO;
        }
        return null;
    }

    /**
     * 根据账号查询用户ID
     *
     * @param accountObjId 账号
     * @return 用户ID
     */
    @Override
    public String findObjIdByAccountObjId(String accountObjId) {
        PersonManageBean personManageBean = this.lambdaQuery().eq(PersonManageBean::getAccountObjId, accountObjId).last(Constants.LAST_SQL).one();
        if(Objects.nonNull(personManageBean)){
            return personManageBean.getObjId();
        }
        return null;
    }

    /**
     * 导入人员信息
     *
     * @param file 导入文件
     * @return 人员信息
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public List<PersonExpVO> importPersonInfo(MultipartFile file) throws GeneralSimpleException {

        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        
        List<PersonExpVO> expVOList = Lists.newArrayList();
        List<PersonManageBean> allPersonInfoList = Lists.newArrayList();
        Iterator<Row> rows = null;
        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = "";
            if(StringUtils.isNotBlank(originalFilename)){
                suffix = FilenameUtils.getExtension(originalFilename);
            }
            rows = PoiTools.getFirstSheetRowsFromFileStream(file.getInputStream(), file.getInputStream(), suffix);
        }catch (Exception e){
            log.error("人员信息导入，获取文件信息异常", e);
        }

        if (Objects.isNull(rows)) {
            throw new GeneralSimpleException("400054");
        }
        
        int count = 0;
        // 记录身份证号的索引号
        Map<String, Integer> cardRowNumberMap = Maps.newHashMap();
        AtomicReference<Integer> id = new AtomicReference<>(getMaxPersonId());
        try {
            while (rows.hasNext()) {
                Row thisRow = rows.next();
                int colIndex = 0;
                count++;
                if (count <= 1) {
                    continue;
                }

                if (PoiTools.isLastRow(thisRow)) {
                    break;
                }

                // 身份证
                String card = PoiTools.getCellStringValue(thisRow.getCell(colIndex++));
                if (StringUtils.isBlank(card)) {
                    continue;
                }
                String name = PoiTools.getCellStringValue(thisRow.getCell(colIndex++));
                if(StringUtils.isBlank(name)){
                    // 装载失败信息
                    expVOList.add(loadExpVO(thisRow.getRowNum(), card, name, "姓名为空"));
                    continue;
                }
                String type = PoiTools.getCellStringValue(thisRow.getCell(colIndex));

                Date birth = null;
                String sex = "";
                if (card.length() == 18) {
                    birth = CardUtil.extractBirthDate(card);
                    sex = CardUtil.extractSex(card);

                    if(Objects.nonNull(birth)){

                        String msg = checkPersonAgeLimit(name, birth);
                        if(StringUtils.isNotBlank(msg)){
                            expVOList.add(loadExpVO(thisRow.getRowNum(), card, name, msg));
                            continue;
                        }
                    }
                }
                if (cardRowNumberMap.containsKey(card)) {
                    // 装载失败信息
                    expVOList.add(loadExpVO(thisRow.getRowNum(), card, name, "表格中导入的身份证号重复录入"));
                } else {
                    // 身份证号未记录过，则在map中登记
                    cardRowNumberMap.put(card, thisRow.getRowNum());
                    // 装载人员信息
                    allPersonInfoList.add(loadPersonBean(card, name, birth, sex, orgId, type));
                }
            }
        }catch (Exception e){
            log.error("参建单位人员信息导入异常", e);
            throw new GeneralSimpleException("400055");
        }

        List<PersonManageBean> savePersonBeanList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(allPersonInfoList)){
            Set<String> existCardList = Sets.newHashSet();
            Map<String, List<PersonManageBean>> existCardMap = Maps.newHashMap();
            
            Map<String, Integer> tempExistCardMap = Maps.newHashMap();

            List<String> cardIdList = allPersonInfoList.stream().map(PersonManageBean::getCard).distinct().collect(Collectors.toList());
            List<PersonManageBean> personManageBeanList = this.lambdaQuery()
                    .in(PersonManageBean::getCard, cardIdList)
                    .list();
            if(CollectionUtils.isNotEmpty(personManageBeanList)){
                existCardMap = personManageBeanList.stream().collect(Collectors.groupingBy(PersonManageBean::getCard));
                existCardList = existCardMap.keySet();
            }

            List<TemporaryAdmissionBean> temporaryAdmissionBeanList = temporaryAdmissionService.lambdaQuery()
                    .in(TemporaryAdmissionBean::getIdNumber, cardIdList)
                    .eq(TemporaryAdmissionBean::getType, BaseCodeConstants.CodeType_AdmissionType.KEY_AdmissionType01)
                    .list();
            if(CollectionUtils.isNotEmpty(temporaryAdmissionBeanList)){
                temporaryAdmissionBeanList.forEach(temporaryAdmissionBean -> {
                    if(!tempExistCardMap.containsKey(temporaryAdmissionBean.getIdNumber())){
                        tempExistCardMap.put(temporaryAdmissionBean.getIdNumber(), temporaryAdmissionBean.getPersonId());
                    }
                });
            }

            if(CollectionUtils.isNotEmpty(existCardList)){
                Set<String> finalExistCardList = existCardList;
                Map<String, List<PersonManageBean>> finalExistCardMap = existCardMap;
                allPersonInfoList.forEach(personInfo -> {
                    if(finalExistCardList.contains(personInfo.getCard())){
                        PersonManageBean personManageBean = finalExistCardMap.get(personInfo.getCard()).get(0);
                        // 如果人员是删除的，则进行唤醒
                        if(StringUtils.equals(personManageBean.getIfDelete(), BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode01)) {
                            personManageBean.setIfDelete(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
                            personManageBean.setName(personInfo.getName());
                            personManageBean.setOrgId(personInfo.getOrgId());
                            savePersonBeanList.add(personManageBean);
                        }else if(!StringUtils.equals(personManageBean.getOrgId(), orgId)){
                            // 导入的证件号不是当前单位的人员
                            String orgInfo = findParentOrgNameInfo(personManageBean.getOrgId());

                            expVOList.add(loadExpVO(cardRowNumberMap.get(personInfo.getCard()), personInfo.getCard(), personInfo.getName(), "当前人员所属单位：" + orgInfo + "，不能重复添加"));
                        }else{
                            expVOList.add(loadExpVO(cardRowNumberMap.get(personInfo.getCard()), personInfo.getCard(), personInfo.getName(), "证件号" + personInfo.getCard() + "已经存在，请确认后重新导入"));    
                        }
                    }else{
                        if(tempExistCardMap.containsKey(personInfo.getCard())){
                            personInfo.setId(tempExistCardMap.get(personInfo.getCard()));
                        }else{
                            personInfo.setId(id.getAndSet(id.get() + 1));    
                        }
                        
                        savePersonBeanList.add(personInfo);
                    }
                });
            }else{
                allPersonInfoList.forEach(allPersonInfo -> {
                    if(tempExistCardMap.containsKey(allPersonInfo.getCard())){
                        allPersonInfo.setId(tempExistCardMap.get(allPersonInfo.getCard()));
                    }else{
                        allPersonInfo.setId(id.getAndSet(id.get() + 1));
                    }
                    savePersonBeanList.add(allPersonInfo);
                });
            
            }
        }
        
        // 排序
        if(CollectionUtils.isNotEmpty(expVOList)){
            expVOList.sort(Comparator.comparing(PersonExpVO::getRowNumber));
        }
        
        if(CollectionUtils.isNotEmpty(savePersonBeanList)){
            this.saveOrUpdateBatch(savePersonBeanList);
        }
        return expVOList;
    }

    /**
     * 单位名称
     * @param personOrgId 用户单位
     * @return 单名名称信息
     */
    private String findParentOrgNameInfo(String personOrgId) {
        OrgBaseInfoVO orgBaseInfoVO = orgService.findById(new OrgIdRequestDTO(personOrgId));
        String orgName = "";
        if(Objects.nonNull(orgBaseInfoVO)){
            orgName = orgBaseInfoVO.getName();
            if(StringUtils.isNotBlank(orgBaseInfoVO.getPid())){
                orgBaseInfoVO = orgService.findById(new OrgIdRequestDTO(orgBaseInfoVO.getPid()));
                if(Objects.nonNull(orgBaseInfoVO)){
                    orgName = orgBaseInfoVO.getName() + "-" + orgName;
                }
            }
        }else{
            // 参建单位
            if(StringUtils.isNotBlank(personOrgId)){
                String name = participatingUnitService.findNameByObjId(personOrgId);
                if(StringUtils.isNotBlank(name)){
                    orgName = "参建单位-" + name;
                }
            }
        }

        if(StringUtils.isBlank(orgName)){
            orgName = "单位信息不存在";
        }

        return orgName;
    }

    /**
     * 导入人员头像
     *
     * @param multipartFile 导入文件
     * @return 人员信息
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public List<PersonExpPictureVO> importProfilePicture(MultipartFile multipartFile) throws GeneralSimpleException {
        String orgId = BaseCommonUtils.extractOrdIdByToken();
        if(StringUtils.isBlank(orgId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }

        boolean isZipPack = true;
        List<PersonExpPictureVO> expPictureVOList = Lists.newArrayList();
        
        // 解压目录
        String packFileStr = IMAGE_BASE_DIR.replace(GET_FILE_PATTERN, "") +
                 File.separator + "zip" + File.separator + BaseCommonUtils.generateUUID();

        packFileStr = packFileStr.replaceAll("//", "/");

        //不存在则创建
        File packFile = new File(packFileStr);
        if (!packFile.exists()) {
            packFile.mkdirs();
        }

        String contentType = multipartFile.getContentType();
        String filename = multipartFile.getOriginalFilename();
        //将压缩包保存在指定路径
        String packFilePath = packFileStr + File.separator + filename;
        if (ZIP_FILE.equals(contentType) || ZIP_FILE2.equals(contentType)) {
            //zip解压缩处理
        } else if (RAR_FILE.equals(contentType) || RAR_FILE2.equals(contentType)) {
            //rar解压缩处理
            isZipPack = false;
        } else if (filename.toLowerCase().endsWith("rar")) {
            //rar解压缩处理
            isZipPack = false;
        } else {
            boolean status = FileTools.testIfImageType(multipartFile);
            if(status){
                String originalFilename = multipartFile.getOriginalFilename();
                String baseName = FilenameUtils.getBaseName(multipartFile.getOriginalFilename());
                PersonManageBean personManageBean = this.lambdaQuery()
                        .eq(PersonManageBean::getCard, baseName)
                        .eq(PersonManageBean::getOrgId, orgId)
                        .last(Constants.LAST_SQL).one();
                if(Objects.nonNull(personManageBean)){
                    if(StringUtils.isBlank(personManageBean.getProfilePicture())){
                        // 不存在头像，则添加头像
                        try {
                            AttachmentImageBean attachmentImageBean = attachmentService.uploadImage(multipartFile, orgId, null);
                            if(Objects.nonNull(attachmentImageBean)){
                                // 保存头像
                                personManageBean.setProfilePicture(attachmentImageBean.getId());

                                boolean status1 = attachmentService.save(attachmentImageBean);
                                if(status1){
                                    status1 = this.updateById(personManageBean);    
                                }
                                
                                if(status1){
                                    return expPictureVOList;
                                }else{
                                   throw new GeneralSimpleException("400056");
                                }
                            }else{
                                expPictureVOList.add(loadExpPictureVO(originalFilename, "保存头像图片失败"));
                            }
                        } catch (GeneralSimpleException e) {
                            log.info("人员信息头像上传，保存头像图片异常", e);
                            expPictureVOList.add(loadExpPictureVO(originalFilename, "保存头像图片异常"));
                        }
                    }else{
                        // 头像存在，则排除
                        expPictureVOList.add(loadExpPictureVO(originalFilename, "人员头像已经存在，请人工确认"));
                    }

                }else{
                    expPictureVOList.add(loadExpPictureVO(originalFilename, "未找到人员信息"));
                }

                return expPictureVOList;
            }
            
            throw new GeneralSimpleException("410187", "上传的压缩包格式不正确,仅支持rar和zip压缩文件!");
        }

        File file = new File(packFilePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            throw new GeneralSimpleException("410187", "解压缩文件到:" + packFileStr + " 失败!");
        }
        if (isZipPack) {
            //zip压缩包
            UnPackUtil.unPackZip(file, packFileStr, FILE_LENGTH);
        } else {
            //rar压缩包
            UnPackUtil.unRARFile(file, packFileStr);
        }
        //删除压缩包
        file.delete();

        List<File> files = Lists.newArrayList();

        // 循环钻取文件
        getFile(files, packFile);

        boolean ftpUploadStatus = false;
        
        Map<String, File> cardFileMap = Maps.newHashMap();
        for (File tempFile : files) {
            cardFileMap.put(FilenameUtils.getBaseName(tempFile.getName()), tempFile);
        }
        List<PersonManageBean> updatePersonBeanList = Lists.newArrayList();
        List<AttachmentImageBean> saveImageBeanList = Lists.newArrayList();
        if(!cardFileMap.isEmpty()){
            Set<String> cardList = cardFileMap.keySet();
            List<PersonManageBean> personManageBeanList = this.lambdaQuery()
                    .in(PersonManageBean::getCard, cardList)
                    .eq(PersonManageBean::getOrgId, orgId)
                    .list();
            if(CollectionUtils.isNotEmpty(personManageBeanList)){
                personManageBeanList.forEach(personManageBean -> {
                    if(cardFileMap.containsKey(personManageBean.getCard())){
                        File cardFile = cardFileMap.get(personManageBean.getCard());
                        if(StringUtils.isBlank(personManageBean.getProfilePicture())){
                            // 不存在头像，则添加头像
                            try {
                                AttachmentImageBean attachmentImageBean = attachmentService.uploadImage(cardFile, orgId, null);
                                if(Objects.nonNull(attachmentImageBean)){
                                    saveImageBeanList.add(attachmentImageBean);
                                    
                                    // 保存头像
                                    personManageBean.setProfilePicture(attachmentImageBean.getId());
                                    updatePersonBeanList.add(personManageBean);
                                }else{
                                    expPictureVOList.add(loadExpPictureVO(cardFile.getName(), "保存头像图片失败"));
                                }
                            } catch (GeneralSimpleException e) {
                                log.info("人员信息头像上传，保存头像图片异常", e);
                                expPictureVOList.add(loadExpPictureVO(cardFile.getName(), "保存头像图片异常"));
                            }
                        }else{
                            // 头像存在，则排除
                            expPictureVOList.add(loadExpPictureVO(cardFile.getName(), "人员头像已经存在，请人工确认"));
                        }

                        // 移除文件
                        cardFileMap.remove(personManageBean.getCard());
                    }
                });
                
                cardFileMap.forEach((k, v) -> expPictureVOList.add(loadExpPictureVO(k, "未找到人员信息")));
            }else{
                cardFileMap.forEach((k, v) -> expPictureVOList.add(loadExpPictureVO(k, "未找到人员信息")));
            }
        }
        
        boolean status = true;
        if(CollectionUtils.isNotEmpty(saveImageBeanList)){
            status = attachmentService.saveBatch(saveImageBeanList);
        }
        
        if(status && CollectionUtils.isNotEmpty(updatePersonBeanList)){
            status = this.updateBatchById(updatePersonBeanList);
            if(status){
                ftpUploadStatus = true;    
            }
        }

        if(status && ftpUploadStatus){
            //删除解压的图片
            boolean delete = deleteFolder(packFileStr);
            log.info("人员头像上传，临时文件删除状态：{}", delete);
        }
        
        return expPictureVOList;
    }

    /**
     * 根据设备号和工程查询未同步的人员ID 未同步人员 -- 道闸
     *
     * @param devSno                设备号
     * @param constructionWorkObjId 工程ID
     * @return 人员ID
     */
    @Override
    public List<Integer> findPersonIdByWorkIdAndNotSync(String devSno, List<String> orgIdList, String constructionWorkObjId, Date date, Integer limit) {
        
        return this.baseMapper.findPersonIdByWorkIdAndNotSync(
                devSno, orgIdList, constructionWorkObjId, date, 
                BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01, 
                BaseCodeConstants.CodeType_AdmissionType.KEY_AdmissionType01, 
                BaseCodeConstants.CodeType_AccessStatus.KEY_AccessStatus01, 
                BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType03,
                limit);
    }

    /**
     * 根据设备号和工程查询未同步的人员ID 所有人员 -- 道闸
     *
     * @param devSno                设备号
     * @param constructionWorkObjId 工程ID
     * @return 人员ID
     */
    @Override
    public List<Integer> findPersonIdByWorkId(String devSno, List<String> orgIdList, String constructionWorkObjId, Date date) {

        return this.baseMapper.findPersonIdByWorkId(
                devSno, orgIdList, constructionWorkObjId, date,
                BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01,
                BaseCodeConstants.CodeType_AdmissionType.KEY_AdmissionType01,
                BaseCodeConstants.CodeType_AccessStatus.KEY_AccessStatus01,
                BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType03);
    }

    /**
     * 根据设备号和工程查询未同步的人员ID 存在有效期 -- 道闸
     *
     * @param devSno                设备号
     * @param constructionWorkObjId 工程ID
     * @return 人员ID
     */
    @Override
    public List<Integer> findPersonIdByExistEffective(String devSno, List<String> orgIdList, String constructionWorkObjId, Date date) {

        return this.baseMapper.findPersonIdByExistEffective(
                devSno, orgIdList, constructionWorkObjId, date,
                BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType01,
                BaseCodeConstants.CodeType_AdmissionType.KEY_AdmissionType01,
                BaseCodeConstants.CodeType_AccessStatus.KEY_AccessStatus01,
                BaseCodeConstants.CodeType_ApprovalFormType.KEY_ApprovalFormType03);
    }
    
    /**
     * 根据身份证号查询人员ID
     *
     * @param card 身份证号
     * @return 人员ID
     */
    @Override
    public Integer findIdByCard(String card) {
        PersonManageBean personManageBean = this.lambdaQuery().eq(PersonManageBean::getCard, card).last(Constants.LAST_SQL).one();
        if(Objects.nonNull(personManageBean)){
            return personManageBean.getId();
        }
        return null;
    }

    /**
     * 查询工程准入信息
     * @param card                  身份证号
     * @param constructionWorkObjId 工程ID
     * @return 准入信息
     */
    @Override
    public List<TemporaryAdmissionCheckWorkVO> findWorkAccess(String card, String constructionWorkObjId) {
        List<PersonManageBean> personManageBeanList = this.lambdaQuery()
                .eq(PersonManageBean::getCard, card)
                .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02)
                .list();
        if(CollectionUtils.isNotEmpty(personManageBeanList)){
            List<String> personIdList = personManageBeanList.stream().map(PersonManageBean::getObjId).collect(Collectors.toList());
            return personAccessRelaService.findWorkAccessByPersonIdInAndConstructionWorkObjId(personIdList, constructionWorkObjId);
        }
        return Lists.newArrayList();
    }

    /**
     * 根据用户ID查询准入工程
     *
     * @param userId 用户ID
     * @return 准入工程ID
     */
    @Override
    public List<String> findAccessWorkIdByUserId(String userId) {
        PersonManageBean personManageBean = this.lambdaQuery().eq(PersonManageBean::getAccountObjId, userId)
                .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02).last(Constants.LAST_SQL).one();
        if(Objects.nonNull(personManageBean)){
            return personAccessRelaService.findWorkIdByPersonIdAndCycleStartGeAndCycleEndLe(personManageBean.getObjId(), DateUtil.beginOfDay(new Date()));
        }
        return null;
    }

    @Override
    public List<String> findAccessWorkIdByUserId() throws GeneralSimpleException {
        String userId = BaseCommonUtils.extractUserIdtByToken();
        //当前用户不具备总部管理员的角色
        if(StringUtils.isBlank(userId)){
            log.info("单位信息不存在");
            throw new GeneralSimpleException("100003");
        }
        PersonManageBean personManageBean = this.lambdaQuery().eq(PersonManageBean::getAccountObjId, userId)
                .eq(PersonManageBean::getIfDelete, BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02).last(Constants.LAST_SQL).one();
        if(Objects.nonNull(personManageBean)){
            return personAccessRelaService.findWorkIdByPersonIdAndCycleStartGeAndCycleEndLe(personManageBean.getObjId(), DateUtil.beginOfDay(new Date()));
        }
        return null;
    }
    
    /**
     * 加载导入头像返回值
     * @param  fileName 身份证号
     * @param msg 信息
     * @return 返回结果
     */
    private PersonExpPictureVO loadExpPictureVO(String fileName, String msg){
        PersonExpPictureVO expPictureVO = new PersonExpPictureVO();
        expPictureVO.setFileName(fileName);
        expPictureVO.setMsg(msg);
        return expPictureVO;
    }

    public void getFile(List<File> allFiles, File file){

        // 判断是否是目录
        if(file.isDirectory()){
            File[] files = file.listFiles();
            if (Objects.nonNull(files)) {
                for(File f : files){
                    getFile(allFiles, f);
                }
            }
        }else{
            allFiles.add(file);
        }
    }

    public static boolean deleteFolder(String folderPath) {
        File folder = new File(folderPath);
        if (folder.exists()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteFolder(file.getPath());
                    } else {
                        file.delete();
                    }
                }
            }
            return folder.delete();
        }
        return false;
    }

    /**
     * 装载导入返回值
     * @param card 证件
     * @param rowNumber 行
     * @param name 姓名
     * @param msg 异常信息
     * @return 返回对象
     */
    private PersonExpVO loadExpVO(Integer rowNumber, String card, String name, String msg){
        // 身份证号ID为空
        PersonExpVO expVO = new PersonExpVO();
        expVO.setRowNumber(rowNumber);
        expVO.setCard(card);
        expVO.setName(name);
        expVO.setMsg(msg);
        return expVO;
    }

    /**
     * 装载人员信息返回值
     * @param card 身份证号
     * @param name 姓名
     * @param birth 生日
     * @param sex 性别
     * @param orgId 组织单位
     * @param type 人员类型
     * @return 人员信息
     */
    private PersonManageBean loadPersonBean(String card, String name, Date birth, String sex, String orgId, String type){
        // 身份证号ID为空
        PersonManageBean personManageBean = new PersonManageBean();
        personManageBean.setObjId(BaseCommonUtils.generateUUID());

        personManageBean.setCard(card);
        personManageBean.setName(name);
        personManageBean.setBirth(birth);
        personManageBean.setSex(sex);
        personManageBean.setOrgId(orgId);
        personManageBean.setType(type);

        personManageBean.setIfDelete(BaseCodeConstants.CodeType_WhetherCode.KEY_WhetherCode02);
        personManageBean.setDataSource("2");
        return personManageBean;
    }

    /**
     * 组装子节点数据
     * @param orgBeanMap 机构实体
     * @param personAllOrgIdSet 用户已经封装数据的单位ID
     * @param orgPersonInfoVOList 树形菜单
     * @return 
     */
    private List<OrgPersonInfoVO> assembleChildrenOrgPersonInfoVO(Map<String, List<OrgBean>> orgBeanMap, List<String> personAllOrgIdSet, List<OrgPersonInfoVO> orgPersonInfoVOList){
        // 所有菜单集(含children)
        List<OrgPersonInfoVO> loopMenus = new ArrayList<>();
        // 设备和部件装载完成，需要对设备和部件进行分级
        // 第一层循环 拿到每一个菜单
        for (OrgPersonInfoVO parent : orgPersonInfoVOList) {
            // 第二层循环 获取每一个菜单的直接子菜单集
            List<OrgPersonInfoVO> children = new ArrayList<>();
            for (OrgPersonInfoVO child : orgPersonInfoVOList) {
                if (Objects.equals(child.getPid(), parent.getObjId())) {
                    children.add(child);
                }
            }
            if(CollectionUtils.isNotEmpty(children)){
                children = children.stream().sorted(Comparator.comparing(OrgPersonInfoVO::getCreateTime)).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(parent.getChildrenList())){
                    parent.getChildrenList().addAll(children);
                }else{
                    parent.setChildrenList(children);
                }
               
            }
            loopMenus.add(parent);
        }

        return resetOrgPersonInfoVO(orgBeanMap, personAllOrgIdSet, loopMenus);
    }

    /**
     * 重排单位信息，去掉已经找到父级的菜单
     * @param orgBeanMap 角色bean
     * @param personAllOrgIdSet 已经登记过单位的ID
     * @param loopMenus 回环数据
     */
    private List<OrgPersonInfoVO> resetOrgPersonInfoVO(Map<String, List<OrgBean>> orgBeanMap, List<String> personAllOrgIdSet, List<OrgPersonInfoVO> loopMenus){
        List<OrgPersonInfoVO> newMenusList = new ArrayList<>();
        List<String> newAddOrdIdList = Lists.newArrayList();
        boolean reset = false;
        // 最后只取父级id为0的菜单
        for (OrgPersonInfoVO resultMenu : loopMenus) {
            if (StringUtils.isEmpty(resultMenu.getPid())) {
                newMenusList.add(resultMenu);
            }else{
                if(!personAllOrgIdSet.contains(resultMenu.getPid())){
                    newMenusList.add(resultMenu);
                    
                    // 上级菜单不存在，则组装上级菜单
                    reset = true;
                    if(!newAddOrdIdList.contains(resultMenu.getPid())){
                        List<OrgBean> orgBeans = orgBeanMap.get(resultMenu.getPid());
                        orgBeans.forEach(orgBean -> {
                            OrgPersonInfoVO orgPersonInfoVO = new OrgPersonInfoVO();
                            BeanUtils.copyProperties(orgBean, orgPersonInfoVO);
                            orgPersonInfoVO.setObjId(orgBean.getId());
                            newMenusList.add(orgPersonInfoVO);

                            // 增加记录
                            newAddOrdIdList.add(orgBean.getId());
                        });
                    }
                }
            }
        }
        
        if(reset){
            personAllOrgIdSet.addAll(newAddOrdIdList);
            return assembleChildrenOrgPersonInfoVO(orgBeanMap, personAllOrgIdSet, newMenusList);
        }else{
            return newMenusList;
        }
    }
    
    /**
     * 根据ID查询人员信息
     * @param personObjId 人员ID
     * @return 人员信息
     * @throws GeneralSimpleException 异常信息
     */
    private PersonManageBean findById(String personObjId) throws GeneralSimpleException {
        PersonManageBean personManageBean = this.getById(personObjId);
        if(Objects.isNull(personManageBean)){
            throw new GeneralSimpleException("400037", personObjId);
        }
        return personManageBean;
    }
}
